import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:delivery_application/common/globs.dart';
import 'package:delivery_application/common/locator.dart';
import 'package:http/http.dart' as http;

//Map 是一种常用的数据结构，表示键值对的集合
typedef ResSuccess = Future<void> Function(Map<String, dynamic>);
typedef ResFailure = Future<void> Function(dynamic);

class ServiceCall {
  //static final NavigationService navigationService =
  //    locator<NavigationService>();
  static Map userPayload = {};
  //static var userID = 0;
  //static var authTocken = "";

  static void post(Map<String, dynamic> parameter, String path,
      {bool isToken = false, ResSuccess? withSuccess, ResFailure? failure}) {
    Future(() {
      try {
        var headers = {'Content-Type': 'application/x-www-form-urlencoded'};

        // if (isToken) {
        //  headers["tocken"] = "";
        //}
        //这段代码通过发送 HTTP POST 请求，将指定的参数数据发送到指定的 URL，并在请求完成时执行相应的处理逻辑
        http
            .post(Uri.parse(path), body: parameter, headers: headers)
            .then((value) {
          if (kDebugMode) {
            print(value.body);
          }

          try {
            var jsonObj =
                json.decode(value.body) as Map<String, dynamic>? ?? {};
            if (withSuccess != null) withSuccess(jsonObj);
          } catch (err) {
            if (failure != null) failure(err.toString());
          }
        }).catchError((e) {
          if (failure != null) failure(e.toString());
        });
      } catch (err) {
        if (failure != null) failure(err.toString());
      }
    });
  }

  //logout功能待开发
  // static logout() {
  //   Globs.udBoolSet(false, Globs.userLogin);
  //   userPayload = {};
  //   navigationService.navigateTo("welcome");
  // }
}
